// Copyright (C) 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.


#include "auth.h"
#include "http_interact.h"

using std::stringstream;

namespace googleapps {

string AuthenticationManager::admin_email_;
string AuthenticationManager::admin_password_;
string AuthenticationManager::domain_;
string AuthenticationManager::token_;
time_t AuthenticationManager::token_time_;

static const unsigned int kSecondsInHour = 3600,
                          kHoursInDay = 24,
                          kDaysTokenValid = 1,
                          kTokenLifetime = kDaysTokenValid * kHoursInDay *
                                           kSecondsInHour;

static const string kClientLoginUrl =
    "https://www.google.com/accounts/ClientLogin";
static const string kTokenPrefix = "SID=";

bool AuthenticationManager::Initialize(const string &admin_email,
                                       const string &admin_password,
                                       const string &domain) {
  admin_email_ = admin_email;
  admin_password_ = admin_password;
  domain_ = domain;

  pair<bool, string> token = RenewToken();
  return token.first;
}

pair<bool, string> AuthenticationManager::RenewToken() {
  pair<bool, string> result = GetAuthToken();

  if (result.first) {
    token_ = result.second;
    token_time_ = time(NULL);
  } else {
    token_ = "";
  }

  return result;
}

pair<bool, string> AuthenticationManager::GetAuthToken() {
  pair<bool, string> result = ExecutePost(kClientLoginUrl,
    "accountType=HOSTED&Email=" + UrlEncode(admin_email_) + "&Passwd=" +
    UrlEncode(admin_password_));

  if (!result.first) {
    return result;
  } else {
    stringstream tokenizer(result.second);
    string cur_line;

    while (true) {
      getline(tokenizer, cur_line);
      if (tokenizer.fail()) break;

      if (cur_line.find(kTokenPrefix) == 0) {
        // We found the line starting with "SID=".  Note that there's
        // no need to URL-decode this string because tokens contain
        // only alphanumeric characters and underscores.
        return make_pair(true, cur_line.substr(kTokenPrefix.length()));
      }
    }

    return make_pair(false, "Response did not contain a valid token.");
  }
}

string AuthenticationManager::get_token() {
  // If the token has expired (i.e. the difference between the current time
  // and the token's timestamp is greater than the token lifetime), renew it.
  if (!token_.empty() && difftime(time(NULL), token_time_) > kTokenLifetime) {
    RenewToken();
  }

  return token_;
}

} // End of googleapps namespace
